package cn.wolfcode.redis.service.impl;

import cn.wolfcode.redis.service.INewsRedisService;
import cn.wolfcode.service.INewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class NewsRedisServiceImpl implements INewsRedisService {
private String prefix="artical:";
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private INewsService newsService;
    @Override
    public long viewnumIncr(Long id) {

        String key = prefix+id;
        Long increment =  redisTemplate.opsForValue().increment(key);

        return increment;
    }

    @Override
    public boolean chijiuhua() {
        Set<String> keys = redisTemplate.keys(prefix+"*");
        for (String key : keys) {
            String viewnumstr = redisTemplate.opsForValue().get(key);
            long viewnum = Long.parseLong(viewnumstr);
            String substring = key.substring(key.indexOf(":") + 1);
            long id = Long.parseLong(substring);
            newsService.updateViewNum(id,viewnum);
        }
        return false;
    }
}
